# -*- coding: UTF-8 -*-
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def send_email(msg, receiver, subject=None):
    smtpserver = 'smtp.partner.outlook.cn' #邮箱服务
    smtp_port = 587
    username = 'noreply.bdp@cootek.cn'
    # username = 'data-noreply@cootek.cn'
    password = 'BDP.noreply1'
    # password = 'HVl81KDvnKbVqEUj'

    smtp = smtplib.SMTP(timeout=70)
    smtp.connect(smtpserver, smtp_port)
    smtp.starttls()

    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = '邮件主题'
    if subject != None:
        # 每小时的监控邮件
        msgRoot['Subject'] = subject
    msgText = MIMEText(msg, 'html', 'utf-8')
    msgRoot.attach(msgText)

    # 持续尝试发送，直到发送成功
    while 1:
        try:
            # 登录邮件服务器
            smtp.login(username, password)
            smtp.sendmail(username, receiver, msgRoot.as_string())  # 发送邮件
            break
        except Exception as e:
            print(str(e))
            try:
                time.sleep(20)
                smtp.connect()  # 连接至邮件服务器
            except Exception as e:
                print(str(e))
                print("failed to login to smtp server")  # 登录失败


if __name__ == '__main__':
    send_email('测试邮件', '2973093577@qq.com', '邮件主题')
